const jwt = require('jsonwebtoken');
const fs = require('fs');
const path = require('path');

//生成token
function generateToken(data) {
    let created = Math.floor(Date.now() / 1000);
    // console.log(created + 3600 * 24 * 7)
    let cert = fs.readFileSync(path.join(__dirname, '../rsa_private_key.pem'));
    let token = jwt.sign({
        data,
        exp: created + 3600 * 24 * 7
        // exp: created + 10
    }, cert, {algorithm: 'RS256'})
    return token;
}

//验证token
function verifyToken(token) {
    let cert = fs.readFileSync(path.join(__dirname, '../rsa_public_key.pem'));
    try {
        let result = jwt.verify(token, cert, {algorithms: ['RS256']}) || {};
        // console.log('verifyToken', result)
        let {exp = 0} = result, current = Math.floor(Date.now() / 1000);
        if (current <= exp) {
            res = result.data || {};
        }
    } catch (e) {
        // console.log('e', e);
        res = 'err'
    }
    // console.log('get token', res);
    return res;
}

function getTime() {
    return new Date().toLocaleString('chinese', {
        hour12: false,
        year: "numeric",
        month: "2-digit",
        day: "2-digit",
        hour: "2-digit",
        minute: "2-digit",
        second: "2-digit"
    })
}

module.exports.generateToken = generateToken;
module.exports.verifyToken = verifyToken;
module.exports.getTime = getTime;